package site.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import neoutil.CommonAction;

import site.entity.Role;
import site.entity.User;
import site.service.RoleRepository;
import site.service.UserRepository;

import com.rain.acm.Sso;

public class SingleSignFilter implements Filter  {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		System.out
				.println("==================================SingleSignFilter=================================");
		System.out.println("Sso.hasLogin()::::" + Sso.hasLogin());
		if (Sso.hasLogin()) {
			Map<String, Object> userInfo = new HashMap<String, Object>();
			userInfo = Sso.myInfo();
			String userName = userInfo.get("username").toString();
			String email = userInfo.get("email").toString();
			String realName = userInfo.get("realname").toString();
			Map<String, String> typeInfo = new HashMap<String, String>();
			typeInfo = (Map<String, String>) userInfo.get("type");
			String typeName = typeInfo.get("name");
			boolean real = (Boolean) userInfo.get("real");

			System.out.println(userName + "\t" + email + "\t" + realName + "\t"
					+ typeName);

			HttpServletRequest req = (HttpServletRequest) request;
			// User user = (User) req.getSession().getAttribute("loginUser");

			User loginUser = new User();
			loginUser.setName(userName);
			loginUser.setRealName(realName);
			loginUser.setEmail(email);
			if (real) {
				loginUser.setReal(true);
			}
			
			UserRepository ur = new UserRepository();
			User usr = ur.getUserByName(userName);
			if(usr!=null){
				loginUser.setId(usr.getId());
				loginUser.setRid(usr.getRid());
			}
			else 
			{
				loginUser.setRid(Role.GUSET);				
			}
			
			req.getSession().setAttribute("loginUser", loginUser);
		}
		else
		{
						
			UserRepository ur = new UserRepository();
			User loginUser = ur.getUserById(10);
			RoleRepository rr = new RoleRepository();
			Role r = rr.getRoleById(loginUser.getRid());
			loginUser.setRid(Role.ADMIN);
			((HttpServletRequest) request).getSession().setAttribute("loginUser", loginUser);
			/**/
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		Timer timer = new Timer();
		int interval = 1000 * 60 * 30;// 每半个小时执行一次任务
		UploadTimerTask task = new UploadTimerTask(interval);
		timer.schedule(task, 0, interval);
	}

}
